
/****** Object:  Stored Procedure [dbo].tblOpicCodeGetList    Script Date: Thursday, October 27, 2011 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sptblOpicCodeGetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sptblOpicCodeGetList]
GO

	
	
	
/******************************************************************************
**		File: 
**		Name: [dbo].sptblOpicCodeGetList
**		Desc: 
**
**		Return values:
** 
**		Called by:   
**              
**		Parameters:
**		Input							Output
**     ----------							-----------
**
**		Auth: CodeSmith
**		Date: 27/10/2011 17:41:38
*******************************************************************************
**		Change History
*******************************************************************************
**		Date:		Author:				Description:
**		--------		--------				-------------------------------------------
**    
*******************************************************************************/
CREATE PROCEDURE [dbo].sptblOpicCodeGetList
	@OrderBy varchar(50),
	@OrderDirection varchar(5),
	@Page int,
	@PageSize int,
	@TotalRecords int output
AS

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

CREATE TABLE #TemptblOpicCode (
	RowNumber INT IDENTITY (1, 1) NOT NULL,
	CustomerName varchar(128),	
	CustomerBranch varchar(3)	
)

DECLARE @sql nvarchar(2000)
DECLARE @Top int

SET @Top = @Page*@PageSize
-- insert primary keys into temp table
SET @sql =	N'INSERT INTO #TemptblOpicCode ([CustomerName],[CustomerBranch]) SELECT '
IF @PageSize > 0
   SET @sql = @sql + ' TOP ' + CAST(@Top as nvarchar)
SET @sql = @sql + ' [CustomerName],[CustomerBranch] FROM [dbo].[tblOpicCode]  ORDER BY [' + @OrderBy + N'] ' + @OrderDirection
EXEC (@sql)


SELECT @TotalRecords = COUNT(*) FROM [tblOpicCode]

SELECT
	[dbo].[tblOpicCode].[CustomerName],
	[dbo].[tblOpicCode].[CustomerBranch],
	[OpicsCode],
	[Portfolio]
FROM
	#TemptblOpicCode AS tblTemp JOIN [dbo].[tblOpicCode] ON
	tblTemp.CustomerName = [dbo].[tblOpicCode].CustomerName  AND 	
	tblTemp.CustomerBranch = [dbo].[tblOpicCode].CustomerBranch 	
WHERE (@PageSize = 0) OR (@PageSize > 0 AND (@Page - 1)*@PageSize < RowNumber AND RowNumber <= @Page*@PageSize)
ORDER BY RowNumber

DROP TABLE #TemptblOpicCode

GO

	
